package com.cheyunkeji.er.receiver;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;

import java.io.File;

public class UpdateVersionReceiver extends BroadcastReceiver {

    // private static final String TAG = "UpdateVersionReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        //  Log.e(TAG, "收到广播");
        long id = context.getSharedPreferences("config", Context.MODE_PRIVATE).getLong("load_id", 0);
        String load_info = context.getSharedPreferences("config", Context.MODE_PRIVATE).getString("load_info", "");
        long reference = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
        DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        if (id == reference) {
            try {
                Uri uri = downloadManager.getUriForDownloadedFile(id);
                Intent intent2 = new Intent();
                intent2.setAction(Intent.ACTION_VIEW);
                intent2.addCategory("android.intent.category.DEFAULT");
                intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                String encodedPath = uri.getEncodedPath();
                if (!encodedPath.endsWith(".apk") && !TextUtils.isEmpty(load_info)) {
                    encodedPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + Environment.DIRECTORY_DOWNLOADS + "/" + load_info;
                }
                Uri uri1 = Uri.fromFile(new File(encodedPath));
                intent2.setDataAndType(uri1,"application/vnd.android.package-archive");
                //     intent2.setData()
                context.startActivity(intent2);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}
